

// always requires an idle view 
#include "kb.h"                 // keybaord event type 
#include "touch_algorithm.h"    // touch event type 
#include "custom_event.h"
#include "gui.h"                // GUI header

#include "views.h"
#include "views_util.h"

#include "xapp_config.h"

#include "xapp_clock.h"
#if USER_CHECK_ENABLED( PEDOMETER )
#include "xapp_pedometer.h"
#endif 
#include "xapp_access.h"
#include "xapp_profile.h"
#include "xapp_localize.h"
#include "algorithm.h"


enum tagPedometer
{
    tagPedometerDragStart,
    tagPedometerToLeft,
    tagPedometerToRight,
    tagPedometerBack,
};

enum flagPedometer
{
    flagPedometerPaintValue,
}; 


GUI_VIEW_FUNC_DECLARE_ALL;
static void local_view_event_handler( uint32_t tag );

static uint8_t string_steps[12];
static uint8_t string_distance[12];
static uint8_t string_calorie[12];  

//static char* p_format_steps;
static char* p_format_distance;
static char* p_format_calorie; 

// 步数
const char steps_format_chinese[] = { 0x25,0x64,0x20,0xE6,0xAD,0xA5, 0 }; // %d 步
const char steps_format_others[] = { 0x25,0x64,0x20,0x73,0x74,0x65,0x70,0x73, 0}; // %d steps

// 公里 中文
const char km_format_chinese[] = {'%','1','.','2','f', ' ', 0xE5,0x85,0xAC,0xE9,0x87,0x8C, 0 };
const char mile_format_chinese[] = {'%','1','.','2','f',' ',0xE8,0x8B,0xB1,0xE9,0x87,0x8C, 0};
// 英文
const char km_format_others[] = {'%','1','.','2','f', ' ', 'k', 'm', 0 };
const char mile_format_others[] = {'%','1','.','2', 'f', ' ', 'm', 'i', 'l', 'e', 0 };

// 卡路里
const char calorie_format_chinese[] = { 0x25,0x64,0x20,0xE5,0x8D,0xA1, 0}; // %d 大卡
const char calorie_format_others[] = { 0x25,0x64,0x20,0x6B,0x63,0x61,0x6C, 0} ; // %d kcal


const static ui_widgets_type_t wglPedometer[] = 
{
        // background 
    [0] = uiPictureBox( IMG_Health_BG_360_360_01, 0, 0, 0, GUI_LCD_RES_H, GUI_LCD_RES_V ),
    //[0] = uiCanvas( 0, 0, GUI_LCD_RES_H, GUI_LCD_RES_V, COLOR_BLACK ),
    // step icon 
    [1] = uiPictureBoxOverlay( IMG_Pedometer_Icon_098_098_01, 0, 132, 36, 98, 98, COLOR_BLACK),

    // distance icon
    [2] = uiPictureBox( IMG_Pedometer_Distance_Calorie_048_050_02, 0, 94 , 190, 48, 50 ),
    // calorie icon
    [3] = uiPictureBox( IMG_Pedometer_Distance_Calorie_048_050_02, 1, 94,  244, 48, 50 ),
    //pedo chinese icon
    [4] = uiPictureBox( IMG_Health_Pedo_Chinese_090_044_01, 0, 135, 295, 90, 44 ),
    
    // step value
    [5] = uiNumberWithBuffer( 0,   135, GUI_LCD_RES_H, SIZE_SCALE(52), COLOR_BLACK, COLOR_WHITE, ALIGN_MIDDLE_TOP, FILL_NONE, ENCODING_ASCII, FONT_ASCII_1_40_52, "%d",string_steps, ARRAY_NUM(string_steps)),
    // distance value
    [6] = uiNumberWithBuffer( 154, 190, GUI_LCD_RES_H, SIZE_SCALE(31), COLOR_BLACK, COLOR_WHITE, ALIGN_LEFT_CENTOR, FILL_NONE, ENCODING_ASCII, FONT_ASCII_1_24_31, "%1.2f km", string_distance, ARRAY_NUM(string_distance)),
    // calorie value
    [7] = uiNumberWithBuffer( 154, 244, GUI_LCD_RES_H, SIZE_SCALE(31), COLOR_BLACK, COLOR_WHITE, ALIGN_LEFT_CENTOR, FILL_NONE, ENCODING_ASCII, FONT_ASCII_1_24_31, "%d kcal", string_calorie, ARRAY_NUM(string_calorie)),

    
};

const static ui_refresh_part_t rectPedometerPart[] = 
{
    [0] = xRECTANGLE( 0, 135, GUI_LCD_RES_H, SIZE_SCALE(40) ),
    [1] = xRECTANGLE( 0, 190, GUI_LCD_RES_H, SIZE_SCALE(24) ),
    [2] = xRECTANGLE( 0, 244, GUI_LCD_RES_H, SIZE_SCALE(24) ),
};


GUI_VIEW_DEF_NR( viewApp_Pedometer ) = 
{
    // name 
    .name = "App+Pedometer",
    
    // init 
    .init = initialize,
    .display_func = display_callback_func,
    .refresh_func_check = display_refresh_func,
    .destroy_func = on_destroy_func,
    .set_parent_func = on_set_parent_func, 
    
    // input 
    .on_touch = on_touch,
    .on_button = on_button,
    .on_event_update = on_event_update,     
    
    .pWidgetlist =  (ui_widgets_type_t*)wglPedometer ,
    .widget_cnt = WIDGET_COUNT( wglPedometer ),

    .flag = GUI_VIEW_FLAG_FUNC | GUI_VIEW_FLAG_ALIVE_DELAY
};


static void reload_format(void)
{
    // if chinese, set format
    const profile_system_t* p_profile_sys = xapp_profile_get_system();

    {
        // p_format_steps = (char*)steps_format_others;
        p_format_calorie = (char*)calorie_format_others;

        if( p_profile_sys->unit == 0 )
        {
            p_format_distance = (char*)km_format_others;
        }
        else 
        {
            p_format_distance = (char*)mile_format_others; 
        }
    }
}

/* 当前view初始化
// 需要指定前使用的控件组
// 自动更新间隔，不使用自动更新间隔则interval = 0
// 指定生命周期，生命周期结束后自动调用 destroy， 测试过程中，可以将Lifetime = 0 使屏幕常亮 
*/
static void initialize(gui_menu_t * menu, void* pvParameter)
{
    menu->interval = 0;
    menu->lifetime = VIEWS_LIFETIME_DEFAULT; 
    
    reload_format();
}
static void on_set_parent_func(gui_menu_t * menu, const gui_view_t * parent)
{
//    p_this_parent = parent;
}
/* 销毁函数
// 在销毁前处理当前信息，比如不允许销毁时，将当前界面状态保存为background。
// true:  允许销毁
// false: 不允许自动销毁，则GUI只关闭当前显示，输入事件仍由当前view进行处理。
          那么view判断当前状态为background时，作出对应background下的按键、触摸等事件反馈
*/
static uint32_t on_destroy_func(gui_menu_t * menu)
{        
    return GUI_DESTROY_RET_DEFAULT; 
}

/* 显示回调
   重新指定参数, 用来获取当前界面的控件组
   ** 当前界面有多个控件组时，应该有条件确定使用哪一组控件组 ** 
*/
static void display_callback_func(gui_menu_t * menu)
{    
    ui_property_t prop;
    ui_widgets_type_t * widgets = menu->widgets;
    uint32_t steps = 0;
    #if USER_CHECK_ENABLED( PEDOMETER )
    const xapp_pedo_desc_t* p_desc = xapp_pedometer_get_desc();
    steps = p_desc->steps;
    #endif 
    
    // widgets[6].uiNumber.format = p_format_steps;
    widgets[6].uiNumber.format = p_format_distance;
    widgets[7].uiNumber.format = p_format_calorie;

    if(xapp_loacl_is_chinese_language())
    {
        widgets[4].visible = 1;
    }
    else
    {
        widgets[4].visible = 0;
    }
    
    if( IS_REQ_SRC_CREATE( menu->source )) 
    {
        if( IS_REQ_SRC_CREATE_SINGLE( menu->source )) 
        {
            gui_part_t part = GUI_PART_CONFIG( rectPedometerPart, 0 );
            gui_part_create( &part );
        }
        FLAG_ALL();
    }
    
    // 局部更新（事件使用局部更新来 重绘步数等显示 ）
    if( menu->source == GUI_VIEW_REQ_SRC_UPDATE_PART )
    {
        FLAG_SETB( flagPedometerPaintValue ); 
    }

    if( FLAG_GETB(flagPedometerPaintValue) )
    {
        // check value is required update 
        prop.number.value = steps;
        gui_widget_update_prop( &widgets[5], &prop );

        prop.number.value = xapp_access_DISTANCE_get( steps ) ;
        gui_widget_update_prop( &widgets[6], &prop );

        prop.number.value = algo_lib_pedo_get_calorie( steps);
        gui_widget_update_prop( &widgets[7], &prop );
    }

    FLAG_CLEAR();
}

/* 刷新显示回调
   根据当前状态，重新绘制指定的控件组 
*/
static int display_refresh_func(gui_menu_t * menu)
{
    return 1;
}

static void on_touch(void* pvParameters, gui_menu_t * menu)
{
    tp_algo_evt_t* touch = (tp_algo_evt_t*)pvParameters;

    switch(touch->type)
    {
        case TP_ALGO_EVT_TYPE_DRAG_X:
        VALUES_SET( x, touch->deltaX );
        local_view_event_handler( tagPedometerDragStart );
        break;

        case TP_ALGO_EVT_TYPE_SLIDE_L:
        local_view_event_handler( tagPedometerToLeft );
        break;

        case TP_ALGO_EVT_TYPE_SLIDE_R:
        local_view_event_handler( tagPedometerToRight );
        break;
        
        default:
        break;
    }
}
/* 界面的按键处理

*/
static void on_button(void* pvParameters, gui_menu_t * menu)
{
    kb_evt_t* kb = (kb_evt_t*)pvParameters;

    switch(kb->type)
    {
        case KB_EVT_CLICK:
        local_view_event_handler( tagPedometerBack );
        break;
    }
}

static void on_event_update(void * pvParameters, gui_menu_t * menu)
{
    custom_evt_t* evt = (custom_evt_t*)pvParameters;

    switch( evt->type )
    {
        case CUSTOM_EVT_TYPE_UNIT_UPDATE:
        reload_format();
        gui_update_part(); // 局部刷新
        break;

        case CUSTOM_EVT_TYPE_LANGUAGE_CHANGE:
        reload_format();
        gui_update_part(); // 局部刷新
        break;

        case CUSTOM_EVT_TYPE_STEPS_UPDATE:
        gui_update_part(); // 局部刷新
        break;
        
        default:
        break;
    }
}

static void local_view_event_handler( uint32_t tag )
{
    const gui_view_t* cur_wf=&viewApp_Pedometer;
    const gui_view_t* next_wf=&viewApp_Heartrate;
    const gui_view_t* prev_wf=views_load_current_watchface();
    
    switch( tag )
    {
        case tagPedometerDragStart:
        {
            int16_t delta_x = VALUES_GET(x);
            if( delta_x > 0 )
            {
                gui_view_create_transition( cur_wf, prev_wf, &manageTransition, delta_x, 0 );
            }
            else 
            {
                gui_view_create_transition( cur_wf, next_wf, &manageTransition, delta_x, 0 );
            }
        }
        break;

        case tagPedometerBack:        
        gui_view_create( views_load_current_watchface() );
        break;

        case tagPedometerToLeft:
        GUI_VIEW_CREATE_NAVIGATE_TO_LEFT( cur_wf, next_wf, 0 );
        break;
    
        case tagPedometerToRight:
        GUI_VIEW_CREATE_NAVIGATE_TO_RIGHT( cur_wf, prev_wf, 0 );
        break;
    }
}


